package com.blog.controller.frontpage;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.Session;

import com.blog.controller.base.BaseServlet;
import com.blog.entity.UserEntity;
import com.blog.entity.UserLoginEntity;
import com.blog.service.frontpage.UserService;

@WebServlet("/login")
public class LoginServlet extends BaseServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");

		// 获得昵称
		String phone = req.getParameter("phone");
		// 获得昵称
		String pwd = req.getParameter("pwd");
		// 获得页面输入的验证码
		//String yzm = req.getParameter("yzm");

		// 定义一个集合保存错误信息
		HashMap<String, Object> ms = new HashMap<>();
		// 校验表单数据
		if (pwd == null || pwd.isEmpty()) {
			ms.put("error", "密码不能为空！");
		}
		/*if (yzm == null || yzm.isEmpty()) {
			ms.put("error", "验证码不能为空！");
		}*/
		/*if (phone == null || phone.isEmpty()) {
			ms.put("error", "手机号不能为空！");
		}*/

		// 获得生成图片的验证码
		//Object checkcode_session = req.getSession().getAttribute("checkcode_session");
		// 进行验证码比对和生成文字是否一致
		/*if (!checkcode_session.equals(yzm)) {
			ms.put("error", "验证码不正确！");
		}*/

		/*
		 * UserService service = new UserService(); UserEntity queryUserForLogin =
		 * service.queryPasswordForLogin(phone); if (queryUserForLogin==null) {
		 * ms.put("error", "用户名或者密码不正确！");
		 * 
		 * }else { if(!queryUserForLogin.getUser_password().equals(pwd)) {
		 * ms.put("error", "用户名或者密码不正确！"); } }
		 */

		if (!ms.isEmpty()) {
			// 重定向到登录页面
			redirect("/login", ms);
			return;
		}else {
			if (phone != null && pwd != null) {
				UserService service = new UserService();
				UserLoginEntity  queryUserForLogin = service.queryPasswordForLogin(phone);
				if (queryUserForLogin != null) {
					if (queryUserForLogin.getUser_phone().equals(phone)) {
						req.getSession().setAttribute("user",queryUserForLogin );
						req.getSession().setMaxInactiveInterval(1800000);
						ms.put("error", "");
						redirect("/index");
					} else {
						//ms.put("error", "用户名或者密码不正确！");
						System.out.println("$#^T%$Y#%^");
						redirect("/login", ms);
					}
				} else {
					ms.put("error", "用户名不存在！");
					redirect("/login", ms);
				}
			}

		}

	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		forward("llpfrontpage/login");
	}
}
